package cn.zhouchao.org.service.impl;

import cn.zhouchao.basic.service.impl.BaseServiceImpl;
import cn.zhouchao.org.domain.Department;
import cn.zhouchao.org.domain.Employee;
import cn.zhouchao.org.mapper.DepartmentMapper;
import cn.zhouchao.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    // 引入Mapper接口
    @Autowired
    private DepartmentMapper departmentMapper;
    // 极限树
    @Override
    public List<Department> tree() {
        List<Department> result = new ArrayList<>();
        // 查询出所有的数据
        List<Department> allDepartments = departmentMapper.findAll();
        // 将 全部的部门数据 转成map key  value
        Map<Long, Department> deptMap = allDepartments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
             // 在内存中组装数据
            for (Department dept : allDepartments) {
                if (null == dept.getParentId()){
                    // 这就是一级数据
                    result.add(dept);
                }else {
                    // 找上一级[子找父id]【再按父上子下顺序拼接】
                    Department parent = deptMap.get(dept.getParentId());
                    parent.getChildren().add(dept);
                }
            }
         return result;
    }
    // 抽屉：通过前端点击部门的id，到后端查所有员工，再通过其id查到该员工所有数据
    @Override
    public List<Employee> findByIdEmp(Long id) {
        return departmentMapper.findByIdEmp(id);
    }

}
